package com.trainfinder.ripper;

import java.io.ByteArrayInputStream;
import java.io.IOException;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.xpath.XPath;
import org.xml.sax.InputSource;

import com.trainfinder.requestor.SimpleHtmlParser;
import com.trainfinder.requestor.UnparsableException;

public class LastDateParser extends AbstractParser implements SimpleHtmlParser {

	public String parseOutwardHTML(String data) throws UnparsableException {

		SAXBuilder saxBuilder = new SAXBuilder(
				"org.apache.xerces.parsers.SAXParser");
		String lastDateStr;

		final Document jdomDocument;
		try {

			jdomDocument = saxBuilder.build(new InputSource(
					new ByteArrayInputStream(data.getBytes())));

			lastDateStr = getTextFromNode("/xhtml:html/xhtml:body/xhtml:div/"
					+ "xhtml:div[@id='center_01']/xhtml:div[2]", jdomDocument);

		

		} catch (JDOMException e) {
			throw new UnparsableException(e);
		} catch (IOException e) {
			throw new UnparsableException(e);
		}
		return lastDateStr;

	}

	public String getTextFromNode(String xPathStr, Document jdomDocument)
			throws UnparsableException {

		String result = "";

		try {
			Element e;
			XPath xp = XPath.newInstance(xPathStr);
			xp.addNamespace(NS);
			e = (Element) xp.selectSingleNode(jdomDocument);
			result = e.getText().trim();
		} catch (NullPointerException e) {
			return null;
		} catch (JDOMException e) {
			throw new UnparsableException(e);
		} catch (Exception e) {
			throw new UnparsableException(e);
		}

		return result;
	}

}
